import { TaEncryptAES } from "./encrypt";

// 本地缓存封装
export const TaCache = {

	// 写入缓存数据，可配置有效时间(毫秒)
	set(name: string, value: any, expire: number = 0): void {
		expire = expire > 0 ? Date.now() + expire : 0
		uni.setStorageSync(name, TaEncryptAES.encrypt(JSON.stringify([value, expire])))
	},

	/* 获取缓存数据 */
	get(name: string, _default: any = null): any {
		try {
			let text = uni.getStorageSync(name)
			if (!text) return _default
			let data: any = JSON.parse(TaEncryptAES.decrypt(text))
			let isExpire = (data[1] || 0) > 0 && data[1] < Date.now()
			return isExpire ? (TaCache.del(name), _default) : data[0]
		} catch (e: any) {
			return _default
		}
	},

	/* 删除缓存数据 */
	del(name: string): void {
		uni.removeStorageSync(name)
	},
}

// Toast 消息处理，最多显示七个汉字
export const TaToast = {

	// 隐藏消息显示
	hide(): void {
		uni.hideToast()
	},

	// 通用消息显示
	show(info: string, type?: any, mask?: boolean, time?: number): Promise<any> {
		return new Promise(resolve => {
			setTimeout(resolve, time || 1600)
			uni.showToast({ mask: mask || false, icon: type || 'none', title: info, duration: time || 1600 })
		})
	},

	// 异常消息显示
	error(info: string, mask?: boolean, time?: number): Promise<any> {
		return this.show(info, 'error', mask, time)
	},

	// 成功消息显示
	success(info: string, mask?: boolean, time?: number): Promise<any> {
		return this.show(info, 'success', mask, time)
	},

	// 确认框架
	confirm(content: string, title: string = '操作确认？'): Promise<any> {
		return new Promise((resolve, reject) => uni.showModal({
			title, content, success: (res) => (res.cancel && reject(), res.confirm && resolve(res))
		}))
	},
}

// Loading 消息处理
export const TaLoading = {

	// 显示加载消息
	show(info?: string, mask?: boolean): void {
		uni.showLoading({ mask: mask || false, title: info || '' })
	},

	// 隐藏加载消息
	hide(): void {
		uni.hideLoading()
	}
}

// 判断是否微信环境
export function TaIsWeChat(): boolean {
	return /MicroMessenger/i.test(navigator.userAgent)
}

// 识别终端类型
export function TaPlatform() {
	let platform: string = '';
	// #ifdef H5
	platform = 'wap'
	// #endif
	// #ifdef MP-WEIXIN
	platform = 'wxapp'
	// #endif
	// #ifdef APP-PLUS
	if (uni.getSystemInfoSync().platform === 'ios') {
		platform = 'iosapp'
	} else {
		platform = 'android'
	}
	// #endif
	return platform || 'unknow'
}